package cloudspace.ui;

import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.util.Clients;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.Textbox;


public class EditableListitem extends Listitem
{
    // ~ Constructors ......................................................

    // ----------------------------------------------------------
    @SuppressWarnings("unchecked")
    public EditableListitem( Listbox listbox )
    {
        this.listbox = listbox;

        Listcell cell = new Listcell();
        appendChild( cell );

        textbox = new Textbox();
        cell.appendChild( textbox );

        textbox.addEventListener( "onCancel", new EventListener()
        {
            public void onEvent( Event event ) throws Exception
            {
                declineChanges();
            }
        } );

        EventListener okListener = new EventListener()
        {
            public void onEvent( Event event ) throws Exception
            {
                if ( textbox.getText().length() == 0 )
                {
                    declineChanges();
                }
                else
                {
                    acceptChanges();
                }
            }
        };

        textbox.addEventListener( "onOK", okListener );
        textbox.addEventListener( "onBlur", okListener );

        listbox.getItems().add( this );
        Clients.scrollIntoView( this );
        textbox.focus();
    }


    // ~ Methods ...........................................................

    // ----------------------------------------------------------
    public void setEditListener( InlineEditListener listener )
    {
        this.listener = listener;
    }


    // ----------------------------------------------------------
    private void acceptChanges()
    {
        listener.accept( textbox.getText() );

        listbox.getItems().remove( this );
    }


    // ----------------------------------------------------------
    private void declineChanges()
    {
        listbox.getItems().remove( this );
    }

    // ~ Static/instance variables .........................................

    private static final long serialVersionUID = -3237365886494487610L;

    private Listbox listbox;

    private Textbox textbox;

    private InlineEditListener listener;
}
